package ren.colorful.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

public class SelfThread {

    private AtomicReference<Thread> lock = new AtomicReference<>();

    public void lock(){
        Thread thread = Thread.currentThread();
        while(!lock.compareAndSet(null,thread)){

        }
    }

    public void unLock(){
        Thread thread = Thread.currentThread();
        lock.compareAndSet(thread,null);
    }

    public static void main(String[] args) {
        final SelfThread selfT = new SelfThread();
        new Thread(()->{
            selfT.lock();
            try {
                TimeUnit.SECONDS.sleep(10L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                selfT.unLock();
            }

        }).start();
    }

}
